package com.hp.bon.sgw.wh.mml.repositories;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.hp.bon.sgw.wh.mml.common.MMLSessionEntity;

public class VCMsgRelayRepository {

	//key: sessionId
	private static ConcurrentMap<String, MMLSessionEntity> relayMsgs = new ConcurrentHashMap<String, MMLSessionEntity>();
	//key: sessionId, value: msg receive time
	private static ConcurrentMap<String, Long> timeoutCtrl = new ConcurrentHashMap<String, Long>();
	
	public static void put(String sessionId, MMLSessionEntity entity){
		timeoutCtrl.put(sessionId, Long.valueOf(entity.getXmlMsg().getMsgTime()));
		relayMsgs.put(sessionId, entity);
	}	
	public static MMLSessionEntity get(String sessionId){
		return relayMsgs.get(sessionId);
	}
	public static MMLSessionEntity remove(String sessionId){
		timeoutCtrl.remove(sessionId);
		return relayMsgs.remove(sessionId);
	}
	
	public static boolean findSessionId(String sessionId){
		if(relayMsgs.get(sessionId)==null){
			return false;
		}
		return true;
	}
	
	/*
	 *  timeout: seconds
	 */
	public static List<String> removeTimeoutSessionIds(long timeout){
		long nowTime = System.currentTimeMillis();
		List<String> sessionIds = new ArrayList<String>();
		Set<Entry<String, Long>> entries = timeoutCtrl.entrySet();
		for(Entry<String, Long> entry : entries){
			Long msgTime = entry.getValue();
			long diff = nowTime - msgTime;
			if(diff >= timeout*1000){
				sessionIds.add(entry.getKey());
			}
		}
		for(String sid : sessionIds){
			timeoutCtrl.remove(sid);
		}
		return sessionIds;
	}
}
